package com.haoxin.ai_course.modules.course.biz;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.haoxin.ai_course.common.utils.HttpJsonResult;
import com.haoxin.ai_course.common.utils.UrlDeal;
import com.haoxin.ai_course.modules.course.entity.AcArticle;
import com.haoxin.ai_course.modules.course.entity.VO.AcArticleVO;
import com.haoxin.ai_course.modules.course.service.AcArticleService;

import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;

/**
 * 答题结果表
 * 
 * @author xingxiangguo
 * @email bugcn@qq.com
 * @date 2022-06-06 09:44:49
 */
@Slf4j
@Component
@Service
public class AcArticleBusiness {
	@Autowired
	private MapperFacade mapperFacade;
	@Autowired
	private AcArticleService acArticleService;
	public HttpJsonResult<List<AcArticleVO>> listByAcCategoryId(int categoryId) {
		HttpJsonResult<List<AcArticleVO>> result = new HttpJsonResult<List<AcArticleVO>>();
		QueryWrapper<AcArticle> qw = new QueryWrapper<AcArticle>();
		qw.lambda().eq(AcArticle::getCategoryId, categoryId);
		qw.lambda().orderByDesc(AcArticle::getId);
		List<AcArticle> list = acArticleService.list(qw);
		List<AcArticleVO> voList = mapperFacade.mapAsList(list, AcArticleVO.class);
		for (AcArticleVO acArticleVO : voList) {
			acArticleVO.setContent(replaceStr(acArticleVO.getContent()));
		}
		result.setData(voList); 
		return result;
	}

	public HttpJsonResult<AcArticleVO> getById(Integer id) {
		 HttpJsonResult<AcArticleVO> result = new  HttpJsonResult<AcArticleVO>();
		AcArticle acArticle = acArticleService.getById(id);
		AcArticleVO acArticleVO = mapperFacade.map(acArticle, AcArticleVO.class);
		acArticleVO.setContent(replaceStr(acArticleVO.getContent()));
		result.setData(acArticleVO);
		return result;
	}
	
	/**
	 * 上传文件到阿里
	 * @param fileInputStream
	 * @param fullPath
	 * @throws FileNotFoundException 
	 * @throws Exception
	 */
	@Async
    public  void uploadVideo(String fileName,String fileId,String filePath) throws FileNotFoundException  {
		
	List<JSONObject> json =	acArticleService.getFileResourse(fileId);
	if(json == null) {
		acArticleService.saveFilePath(fileId,fileName,filePath);
	}
		
		FileInputStream fileInputStream = new FileInputStream(new File(filePath));
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tPCZdcUUCLuSkY9gUo6";
        String accessKeySecret = "0Uh2ysqmcvnOBkRkuaL9Q1jMFR8un6";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ai-class-pro";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "assets/";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        
        try {
        	log.info("上传视频到阿里oss开始");
        	long startTime = System.currentTimeMillis();
             ossClient.putObject(bucketName, objectName+fileName, fileInputStream);
             QueryWrapper<AcArticle> qw = new QueryWrapper<AcArticle>();
             qw.lambda().eq(AcArticle::getFileId,  fileId);
             List<AcArticle>list = acArticleService.list(qw);
             if(CollectionUtils.isNotEmpty(list)) {
            	 for (AcArticle acArticle : list) {
            		 acArticle.setUploadStatus(1);
            		 log.info("修改的数据："+JSONObject.toJSONString(acArticle));
            		 acArticleService.updateById(acArticle);
				}
             }
             log.info("上传视频到阿里oss结束，用时："+(System.currentTimeMillis()-startTime));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
	public  void uploadVideoTask(String fileName,String fileId,String filePath) throws FileNotFoundException  {
		FileInputStream fileInputStream = new FileInputStream(new File(filePath));
		// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
		String endpoint = "oss-cn-beijing.aliyuncs.com";
		// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
		String accessKeyId = "LTAI5tPCZdcUUCLuSkY9gUo6";
		String accessKeySecret = "0Uh2ysqmcvnOBkRkuaL9Q1jMFR8un6";
		// 填写Bucket名称，例如examplebucket。
		String bucketName = "ai-class-pro";
		// 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
		String objectName = "assets/";
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		
		try {
			log.info("上传视频到阿里oss开始");
			long startTime = System.currentTimeMillis();
			ossClient.putObject(bucketName, objectName+fileName, fileInputStream);
			QueryWrapper<AcArticle> qw = new QueryWrapper<AcArticle>();
			qw.lambda().eq(AcArticle::getFileId,  fileId);
			List<AcArticle>list = acArticleService.list(qw);
			if(CollectionUtils.isNotEmpty(list)) {
				for (AcArticle acArticle : list) {
					acArticle.setUploadStatus(1);
					log.info("修改的数据："+JSONObject.toJSONString(acArticle));
					acArticleService.updateById(acArticle);
				}
			}
			log.info("上传视频到阿里oss结束，用时："+(System.currentTimeMillis()-startTime));
			
		} catch (OSSException oe) {
			System.out.println("Caught an OSSException, which means your request made it to OSS, "
					+ "but was rejected with an error response for some reason.");
			System.out.println("Error Message:" + oe.getErrorMessage());
			System.out.println("Error Code:" + oe.getErrorCode());
			System.out.println("Request ID:" + oe.getRequestId());
			System.out.println("Host ID:" + oe.getHostId());
		} catch (ClientException ce) {
			System.out.println("Caught an ClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with OSS, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message:" + ce.getMessage());
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
	}
	public  void uploadImage(InputStream fileInputStream,String fullPath,String fileId)  {
		// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
		String endpoint = "oss-cn-beijing.aliyuncs.com";
		// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
		String accessKeyId = "LTAI5tPCZdcUUCLuSkY9gUo6";
		String accessKeySecret = "0Uh2ysqmcvnOBkRkuaL9Q1jMFR8un6";
		// 填写Bucket名称，例如examplebucket。
		String bucketName = "ai-class-pro";
		// 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
		String objectName = "assets/";
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		
		try {
			log.info("上传视频到阿里oss开始");
			long startTime = System.currentTimeMillis();
			ossClient.putObject(bucketName, objectName+fullPath, fileInputStream);
			QueryWrapper<AcArticle> qw = new QueryWrapper<AcArticle>();
			qw.lambda().eq(AcArticle::getFileId,  fileId);
			List<AcArticle>list = acArticleService.list(qw);
			if(CollectionUtils.isNotEmpty(list)) {
				for (AcArticle acArticle : list) {
					acArticle.setUploadStatus(1);
					log.info("修改的数据："+JSONObject.toJSONString(acArticle));
					acArticleService.updateById(acArticle);
				}
			}
			log.info("上传视频到阿里oss结束，用时："+(System.currentTimeMillis()-startTime));
		} catch (OSSException oe) {
			System.out.println("Caught an OSSException, which means your request made it to OSS, "
					+ "but was rejected with an error response for some reason.");
			System.out.println("Error Message:" + oe.getErrorMessage());
			System.out.println("Error Code:" + oe.getErrorCode());
			System.out.println("Request ID:" + oe.getRequestId());
			System.out.println("Host ID:" + oe.getHostId());
		} catch (ClientException ce) {
			System.out.println("Caught an ClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with OSS, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message:" + ce.getMessage());
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
	}
	 private String replaceStr(String content) {
	    	content = UrlDeal.decodeURIComponent(content);
	    	log.info("-------替换前-------："+content);
	    	String result = "";
	    	HashMap<String,String> map = new HashMap<String,String>();
	    	map.put("%23", "#");
	    	map.put("%26", "&");
	    	map.put("%3B", ";");
	    	Set<String> keys = map.keySet();
	    	for (String key : keys) {
	    		content = content.replaceAll(key, map.get(key));
			}
	    	log.info("-------替换后-------："+content);
	    	result = 	UrlDeal.encodeURIComponent(content);
	    	return result;
	    }
	

}
